﻿using System;
using System.Reflection;

namespace USClientKernel.Common.Helper
{
    public class ReflectionHelper
    {
        /// <summary>
        /// 创建对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="nameSpace">命名空间</param>
        /// <param name="className">类型名</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string nameSpace, string className)
        {
            //string path = fullName + "," + assemblyName;        //命名空间.类型名,程序集
            //Type o = Type.GetType(path);                        //加载类型
            //object obj = Activator.CreateInstance(o, true);     //根据类型创建实例
            //return (T)obj;                                      //类型转换并返回
            return CreateInstance<T>(nameSpace, className, Assembly.GetExecutingAssembly().FullName);
        }


        /// <summary>
        /// 创建对象实例
        /// </summary>
        /// <typeparam name="T">要创建对象的类型</typeparam>
        /// <param name="assemblyName">类型所在程序集名称</param>
        /// <param name="nameSpace">类型所在命名空间</param>
        /// <param name="className">类型名</param>
        /// <returns></returns>
        public static T CreateInstance<T>(string nameSpace, string className, string assemblyName)
        {
            try
            {
                string fullName = nameSpace + "." + className;      //命名空间.类型名
                string path = fullName + "," + assemblyName;        //命名空间.类型名,程序集
                Type o = Type.GetType(path);                        //加载类型
                object obj = Activator.CreateInstance(o, true);     //根据类型创建实例
                return (T)obj;                                      //类型转换并返回
            }
            catch
            {
                //发生异常，返回类型的默认值
                return default(T);
            }
        }

    }
}
